<?php
//虚拟数据
// $arr = array("base_resp"=>array("ret"=>"0"));
// print_r(json_encode($arr));
// exit;
//微信账号验证
$arr = array(
    'username'=>$_POST['user'], //wx公众帐号
    'pwd'=>md5($_POST['pass']), //wx公众帐号密码
    'f'=>'json'
 //'imagecode' => $_POST['code'];
);

if (isset($_POST['code'])) {
    $arr['imgcode'] = $_POST['code'];
}

$file = dirname(__FILE__).'/cookie/cookie_'.$arr['username'].'.txt';

// ../cookie/cookie_jcs3800.txt

$headers = array(
    'User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36',
    'Referer:https://mp.weixin.qq.com/',
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://mp.weixin.qq.com/cgi-bin/login');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt($curl, CURLOPT_TIMEOUT, 10 );   
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($arr));
curl_setopt($curl, CURLOPT_HTTPHEADER,$headers);

if (!empty($arr['imgcode'])) {
    curl_setopt($curl, CURLOPT_COOKIEFILE, $file);
}

$result = curl_exec ($curl);
curl_close ( $curl );
$json_arr = json_decode($result);
if ($json_arr->base_resp->ret==0) {
    include_once '/var/www/html/new/com.inc.php';
    $hash = $_SESSION['account'];
    $password = md5(md5($arr['pwd']));
    $token = md5($_SERVER['REQUEST_TIME'].'pft'.$username);
    $encodingAESKey = str_shuffle($token . substr($token, 0, 11));

    $sqlChk = "SELECT id FROM pft_wx WHERE username='{$arr['username']}' LIMIT 1";
    $GLOBALS['le']->query($sqlChk);
    if ($GLOBALS['le']->fetch_assoc()) {
        echo '{"status":"fail","msg":"公众号['.$arr['username'].']已经与票付通平台绑定，请登陆微信公众平台->开发者中心检查服务器配置"}';
    }
    else {
        $sql = <<<SQL
    INSERT INTO pft_wx (fid,`hash`,username,password,token,encodingAESKey,
    create_time) VALUES({$_SESSION['sid']},'{$hash}','{$arr['username']}',
    '{$password}','{$token}','{$encodingAESKey}',now())
SQL;
        $GLOBALS['le']->query($sql);
        $arr = array(
            "status"        => "ok",
            "msg"           => "验证成功",
            "url"           => "http://wx.12301.cc/api.php?hash={$hash}",
            "token"         => $token,
            "encodingAESKey"=> $encodingAESKey
        );
        echo json_encode($arr);
    }
} else {
    $err_msg_arr = array(-21=>'账号不存在或密码错误');
    echo '{"status":"fail","msg":"'.$err_msg_arr[$json_arr->base_resp->ret].'","code":"'.$json_arr->base_resp->ret.'"}';
}


